package com.jy.appmarket.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.text.TextUtils;

public class BitmapUtils {

	public static Bitmap getApplicationIconBitmap(Context ctx, String packageName) {
		if (ctx == null || TextUtils.isEmpty(packageName)) {
			return null;
		}
		PackageManager pm = ctx.getPackageManager();
		try {
			Drawable drawable = pm.getApplicationIcon(packageName);
			return drawable2Bitmap(drawable);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static boolean saveBitmap2File(File file, Bitmap bmp) {
		FileOutputStream out = null;
		try {
			if (file.exists()) {
				file.delete();
			}
			out = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOTools.safeClose(out);
		}
		return false;
	}

	public byte[] bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	public static Drawable bitmap2Drawable(Bitmap bitmap, Context contex) {
		Resources res = contex.getResources();
		BitmapDrawable bd = new BitmapDrawable(res, bitmap);
		return bd;
	}

	/**
	 * Drawable 转 bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawable2Bitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable) drawable).getBitmap();
		} else if (drawable instanceof NinePatchDrawable) {
			Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
					drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
			Canvas canvas = new Canvas(bitmap);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
			drawable.draw(canvas);
			return bitmap;
		} else {
			return null;
		}
	}

	public static void saveBitmap(Bitmap bitmap, String path) {
		FileOutputStream out = null;
		try {
			File file = new File(path);
			out = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOTools.safeClose(out);
		}
	}
}
